<template>
  <div class="body">
    <p class="title">菜单管理</p>
    <!-- 输入框内容 -->
    <div class="search_box">
      <div class="input_box">
        <div class="input_box_item">
          <el-input class="element_input" v-model="searchName" placeholder="请输入菜单名称名" @input="searchData"></el-input>
          <el-select class="element_input" v-model="searchType" clearable @change="searchData" placeholder="请选择菜单类型">
            <el-option label="菜单" :value="1">菜单</el-option>
            <el-option label="功能" :value="2">功能</el-option>
          </el-select>
        </div>
        <el-button type="primary" class="new_btn" @click="addShow(formRef)">新增</el-button>
      </div>
    </div>
    <el-table :data="pageCount" style="width: 100%; margin-top: 20px; margin-bottom: 20px;" row-key="id" border
      stripe="boolean">
      <el-table-column prop="id" label="序号" align="center" />
      <el-table-column prop="title" label="页面标题" align="center" />
      <el-table-column prop="path" label="路径" align="center" />
      <el-table-column prop="icon" label="图标" align="center" />
      <el-table-column prop="type" label="类型" align="center">
        <template #default="scope">
          {{ scope.row.type == 1 ? "菜单" : "功能" }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" sortable align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button class="btn" type="primary" @click="editData(scope.row)">编辑</el-button>
            <el-button class="btn" v-if="scope.row.id !== 1" @click="deletePopShow(scope.row.id)" type="danger">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_box">
      <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.length" />
    </div>
    <div class="bottom_box"></div>

    <el-dialog v-model="dialogVisible" title="添加" width="900">
      <el-form ref="formRef" :model="employeeForm" :rules="formRules">
        <el-form-item prop="pid" label="上级菜单">
          <!-- 上级菜单 -->
          <el-tree-select v-model="employeeForm.pid" :data="topData" check-strictly class="form_input"
            placeholder="请输入上级菜单" />
        </el-form-item>
        <el-form-item prop="title" label="菜单标题">
          <!-- 菜单标题 -->
          <el-input v-model="employeeForm.title" class="form_input" placeholder="请输入菜单标题" clearable />
        </el-form-item>
        <el-form-item prop="path" label="菜单路径">
          <!-- 菜单路径 -->
          <el-input v-model="employeeForm.path" class="form_input" placeholder="请输入菜单路径" clearable />
        </el-form-item>
        <el-form-item prop="icon" label="菜单图标">
          <!-- 图标选择器 -->
          <IconSelector v-model="employeeForm.icon" placeholder="请选择菜单图标" clearable />
        </el-form-item>
        <el-form-item prop="type" label="菜单图标">
          <!-- 图标选择器 -->
          <el-radio-group v-model="employeeForm.type">
            <el-radio :value="1" size="large">菜单</el-radio>
            <el-radio :value="2" size="large">功能</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="sort" label="菜单排序">
          <!-- 菜单排序 -->
          <el-input v-model="employeeForm.sort" class="form_input" type="number" placeholder="请输入菜单排序" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false; formRef?.resetFields();">取消</el-button>
          <el-button type="primary" @click="appendData(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 删除弹窗显示 -->
    <el-dialog v-model="deletePop" title="删除员工" width="500">
      <div class="delete_title">
        <img src="/src/assets/warn.png" alt="">
        <span>确定要删除这些员工吗?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deletePop = false">取消</el-button>
          <el-button type="primary" @click="deleteAffirm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, defineAsyncComponent } from 'vue';// 引入ref和computed
import { menuList, menuAdd, menuDel } from '/@/api/login/index';//引入当前的接口封装
import type { FormInstance, FormRules, UploadFile, } from 'element-plus'
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));
import { ElMessage } from 'element-plus';
import { log } from 'console';
// 全局数据
const data = ref<any[]>([]);
const pageData = ref<any[]>([]);
// 声明当前的页码
const currentPage = ref(1);
// 声明当前页面渲染的数据条数
const pageSize = ref(10);
// 顶级数据声明
const topData = ref<any[]>([]);
// 搜索
const searchName = ref('');
const searchType = ref('');

// 列表接口请求
menuList().then((res) => {
  buildTreeEnhanced(res.data);
});
// 构建二级数据
const buildTreeEnhanced = (datas: any): any => {
  if (!Array.isArray(datas) || datas.length === 0) {
    return [];
  }
  const nodeMap: { [key: number]: any } = {};
  const tree: any[] = [];
  const orphanNodes: any[] = [];
  // 构建原始树结构（不包含顶级节点）
  datas.forEach(item => {
    if (!nodeMap[item.id]) {
      nodeMap[item.id] = {
        value: item.id,
        label: item.title,
        ...item,
        children: []
      };
    }
    const parentNode = nodeMap[item.pid];
    if (item.pid === 0) {
      tree.push(nodeMap[item.id]);
    } else if (parentNode) {
      parentNode.children.push(nodeMap[item.id]);
    } else {
      orphanNodes.push(nodeMap[item.id]);
    }
  });

  // 原始树结构（不包含顶级节点）
  data.value = [...tree];          // 拷贝原始树
  pageData.value = [...tree];      // 拷贝原始树

  // 单独构建 topData（添加顶级节点 + 原始树作为子节点）
  const topLevelNode = {
    id: 0,
    pid: 0,
    title: "顶级数据",
    value: 0,
    label: "顶级数据",
    children: []            // 原始树作为子节点
  };
  topData.value = [topLevelNode, ...tree];   // 仅 topData 包含顶级节点

  return tree;
};

// 计算分页数据
const pageCount = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});

// 页码改变事件
const pageChange = (val: any) => {
  currentPage.value = val;
};

// 每页条数改变事件
const pageNum = (val: any) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

// 添加弹窗的状态
const dialogVisible = ref(false)

// 定义表单数据类型
interface EmployeeForm {
  // 上级id
  pid: null;
  // 菜单名称
  title: string;
  // 菜单路径
  path: string;
  // 图标名称
  icon: string;
  // 类型
  type: number;
  // 排序
  sort: number;
}

// 初始化表单数据
const employeeForm = reactive<EmployeeForm>({
  pid: null,
  title: '',
  path: '',
  icon: '',
  type: 1,
  sort: 0
})
const formRef = ref<FormInstance>();
// 表单验证规则
const formRules = reactive<FormRules<EmployeeForm>>({
  pid: [
    { required: true, message: '请选择上级菜单', trigger: 'blur' },
  ],
  title: [
    { required: true, message: '请输入菜单标题', trigger: 'blur' },
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' },
  ],
  icon: [
    { required: true, message: '请选择菜单图标', trigger: 'blur' },
  ]
});
// 添加确认函数
const appendData = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = {
        id: editId.value,
        pid: employeeForm.pid,
        title: employeeForm.title,
        path: employeeForm.path,
        icon: employeeForm.icon,
        type: employeeForm.type,
        sort: employeeForm.sort
      }
      menuAdd(formData).then(res => {
        if (res.code == 1) {
          ElMessage.success('操作成功');
          dialogVisible.value = false;
          // 重置表单
          formRef.value?.resetFields();
        } else {
          ElMessage.error('操作失败');
        }
      }).catch(err => {
        ElMessage.error(err);
      })
    }
  })
}
const editId = ref(null);
// 编辑回显函数
const editData = (item: any) => {
  dialogVisible.value = true;
  editId.value = item.id;
  employeeForm.pid = item.pid;
  employeeForm.title = item.title;
  employeeForm.path = item.path;
  employeeForm.icon = item.icon;
  employeeForm.type = item.type;
  employeeForm.sort = item.sort;
}

// 删除弹窗状态
const deletePop = ref(false);
const deleteId = ref(0);
const deletePopShow = (item: any) => {
  deletePop.value = true;
  deleteId.value = item;
};
// 删除确认事件
const deleteAffirm = () => {
  menuDel({ id: deleteId.value }).then(res => {
    if (res.code == 1) {
      ElMessage.success('删除成功');
      deletePop.value = false;
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}

// 搜索函数
const searchData = () => {
  const filteredData = computed(() => {
    // 无搜索词时返回全部数据
    if (!searchName.value && !searchType.value) {
      return pageData.value = data.value;
    }
    console.log(searchName.value);

    return data.value.filter(item => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !searchName.value ||
        (item.title && item.title.toString().toLowerCase().includes(searchName.value.toLowerCase()));
      const typeMatch = !searchType.value ||
        (item.type && item.type.toString() == searchType.value.toString());
      return nameMatch && typeMatch;
    });
  });
  pageData.value = filteredData.value;
};

const addShow = (formEl: FormInstance | undefined) => {
  dialogVisible.value = true;
  editId.value = null;
  if (!formEl) return
  formEl.resetFields();
}

</script>

<style scoped>
.body {
  padding: 20px;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.title {
  font-weight: 400;
  font-size: 25px;
}

.input_box {
  width: 100%;
  display: flex;
  margin-top: 15px;
  align-items: center;
  justify-content: space-between;
}

.input_box_item {
  width: 50%;
  display: flex;
  margin-top: 15px;
  align-items: center;
  justify-content: space-between;
}

.element_input {
  width: 48%;
}

.new_btn {
  height: 35px;
  background-color: #0052CC;
  border: 1px solid #0052CC;
}

.new_btn:hover {
  background-color: #4d82d1;
  border: 1px solid #4d82d1;
}

.new_btn:active {
  background-color: #00388b;
  border: 1px solid #00388b;
}

.page_box {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom_box {
  width: 100%;
  height: 30px;
}

.delete_title {
  display: flex;
}

.delete_title img {
  width: 20px;
  margin-right: 10px;
}

.btn{
  height: 30px;
  padding: 0px 15px;
}
</style>